<?php
if(strpos($config['DB_HOST'] , ",") !== false )
{
	$db_host = explode(",",$config['DB_HOST']);
	$m_host = $db_host[0];							//主库ip
	unset($db_host[0]);								//去除主库
	$s_host = implode(",",$db_host);				//从库ip

	$config['DB_HOST'] = $m_host;
	$config['DB_SLAVE_HOST'] = $s_host;
}


class DB{

	protected $sqlstr = '';
	protected $where = '';
	protected $field = '';	
	protected $limit = '';
	protected $order = '';
	protected $group = '';
	protected $having ='';

	protected $join = array();
	protected $config = array();
	protected $options =   array();

	protected $db_id = '';
	
	public function __construct(){
		global $config;
		$this->config = $config;
	}

	public function clear_protected()
	{
		$this->sqlstr = '';
		$this->where = '';
		$this->field = '';	
		$this->limit = '';
		$this->order = '';
		$this->group = '';
		$this->having ='';

		$this->join = array();
		$this->options =   array();

		$this->db_id = '';
	}

	//重组where
	public function where($where = array())
	{
		$where_arry = array();

		if(isset($where['_logic']))
		{
			$act = $where['_logic'];
			unset($where['_logic']);
		}else{
			$act = 'and';
		}

		foreach($where as $obj=>$val)
		{
			if(!is_array($val))
			{
				$where_arry[] = $obj."=".$val;
			}else{
				switch(strtolower($val[0]))
				{
					case 'like':
						$where_arry[] = $obj." like '%".$val[1]."%'";
						break;
					case 'not like':
						$where_arry[] = $obj." not like '%".$val[1]."%'";
						break;
					case 'in':
						$where_arry[] = $obj." in (".implode(",",$val[1]).")";
						break;
					case 'not in':
						$where_arry[] = $obj."not in (".implode(",",$val[1]).")";
						break;
					case 'neq':
						$where_arry[] = $obj."<>".$val[1];
						break;
					case 'gt':
						$where_arry[] = $obj.">".$val[1];
						break;
					case 'egt':
						$where_arry[] = $obj.">=".$val[1];
						break;
					case 'lt':
						$where_arry[] = $obj."<".$val[1];
						break;
					case 'elt':
						$where_arry[] = $obj."<=".$val[1];
						break;
				}
			}
			
		}

		if($where_arry)
		{
			$this->where = implode(" ".$act." ",$where_arry);
		}
		
		return $this;
	}

	//重组limit语句
	public function limit($start = 0,$limit = 10)
	{
		$this->limit = " limit ".$start.",".$limit;
		return $this;
	}

	//重组order排序语句
	public function order($order = '')
	{
		if($order){
			$this->order = " order by ".$order;
		}
		return $this;
	}

	//重组field语句
	public function field($field = '')
	{
		if($field)
		{
			$this->field = $field;
		}else{
			$this->field = " * ";
		}
		return $this;	
	}

	//重组join语句
	public function join($join_str , $direction)
	{
		$this->join[] = $direction." join ".$join_str;
		return $this;
	}

	//重组group语句
	public function group($group)
	{
		$this->group = 'GROUP BY '.$group;
	}

	//重组having语句
	public function having($having)
	{
		$this->having = 'having '.$having;
	}

	//连接数据库方法
	//$act_type write 为写 否则 读
	public function connect($act_type)
	{
		if(strtolower($act_type) == 'write')
		{
			$db_host = $this->config['DB_HOST'];
		}else{
			if($this->config['DB_SLAVE_HOST'])		//是否存在从库
			{
				if(strpos($this->config['DB_SLAVE_HOST'],','))
				{
					$db_arry = explode(",",$this->config['DB_SLAVE_HOST']);
					$rid = rand(0,count($db_arry)-1);

					$db_host = $db_arry[$rid];
				}else{
					$db_host = $this->config['DB_SLAVE_HOST'];
				}				
			}else{
				$db_host = $this->config['DB_HOST'];
			}
		}

		$pdo = new PDO("mysql:host=".$db_host.";port=".$this->config['DB_PORT'].";dbname=".$this->config['DB_NAME'],$this->config['DB_USER'],$this->config['DB_PWD'],array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ".$this->config['DB_CHARSET'].";", PDO::ATTR_ERRMODE =>  PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
		return $pdo;
	}

	//关闭数据连接
	public function close_connect($pdo)
	{
		$pdo = null;
	}

	//select 返回数据方法
	//$table 表名
	public function select($table)
	{
		if($this->field == '')
		{
			$this->field = '*';
		}

		$sqlstr = "select ".$this->field." from ".$table." ";

		if($this->join)
		{
			$sqlstr .= implode(" ",$this->join);
		}

		if($this->where)
		{
			$sqlstr .= " where ".$this->where;
		}

		if($this->group)
		{
			$sqlstr .= $this->group;
		}

		if($this->having)
		{
			$sqlstr .= $this->having;
		}

		if($this->order)
		{
			$sqlstr .= $this->order;
		}

		if($this->limit)
		{
			$sqlstr .= $this->limit;
		}
		
		$pdo = $this->connect('read');

		$result = $pdo->query($sqlstr);

		$this->clear_protected();
		$this->close_connect($pdo);
		return $result->fetchAll();
	}

	//修改数据
	//table 表名	data 修改数组	where 条件
	public function update($table,$data)
	{
		
		$sqlstr = "update ".$table." set ";

		foreach($data as $obj=>$val)
		{
			$sqlstr .= " ".$obj."='".$val."' ";
		}

		if($this->where)
		{
			$sqlstr .= " where ".$this->where;
		}

		$pdo = $this->connect('write');

		$result['record'] = $pdo->exec($sqlstr);	//影响条数

		if($result['record'] > 0)
		{
			$result['status'] = 1;					//操作成功
		}else{
			$result['status'] = 0;					//操作失败
		}

		$this->clear_protected();
		$this->close_connect($pdo);

		return $result;
	}

	//删除方法
	//table 表名	where 条件
	public function delete($table)
	{
		$sqlstr = "delete from ".$table." ";

		if($this->where)
		{
			$sqlstr .= " where ".$this->where;
		}

		$pdo = $this->connect('write');

		$result['record'] = $pdo->exec($sqlstr);	//影响条数

		if($result['record'] > 0)
		{
			$result['status'] = 1;					//操作成功
		}else{
			$result['status'] = 0;					//操作失败
		}

		$this->clear_protected();
		$this->close_connect($pdo);

		return $result;
	}

	//insert 数据
	//table 表名	data数据
	public function insert($table,$data)
	{
		$sqlstr = "insert into ".$table." ";

		
		foreach($data as $obj=>$val)
		{
			$sql1[] = '`'.$obj."`";
			$sql2[] = "'".$val."'";
		}

		$sqlstr = $sqlstr .'('. implode(',',$sql1) .') value ('. implode(",",$sql2) .' )';
		
		$pdo = $this->connect('write');

		$result['record'] = $pdo->exec($sqlstr);	//影响条数

		if($result['record'] > 0)
		{
			$result['status'] = 1;					//操作成功
		}else{
			$result['status'] = 0;					//操作失败
		}

		$this->clear_protected();
		$this->close_connect($pdo);

		return $result;
	}

	//find查找数字
	public function find($table)
	{
		if($this->field == '')
		{
			$this->field = '*';
		}

		$sqlstr = "select ".$this->field." from ".$table." ";

		if($this->where)
		{
			$sqlstr .= " where ".$this->where;
		}
		
		$pdo = $this->connect('read');
		
		$pdo_result = $pdo->query($sqlstr);
		$rs = $pdo_result->fetchAll();

		if($rs)
		{
			$result = $rs[0];
		}else{
			$result = array();
		}
		
		$this->clear_protected();
		$this->close_connect($pdo);

		return $result;
	}

	//query 执行复杂型查询
	public function query($sqlstr)
	{
		$pdo = $this->connect('read');

		$result = $pdo->query($sqlstr);

		$this->clear_protected();
		$this->close_connect($pdo);
		return $result->fetchAll();
	}

	//query 执行复杂型写入
	public function execute($sqlstr)
	{
		$pdo = $this->connect('write');

		$result['record'] = $pdo->exec($sqlstr);	//影响条数

		if($result['record'] > 0)
		{
			$result['status'] = 1;					//操作成功
		}else{
			$result['status'] = 0;					//操作失败
		}

		$this->clear_protected();
		$this->close_connect($pdo);
		return $result;
	}
}
?>